<script lang="ts" setup>
import { ref, reactive, watch, computed, defineEmits } from 'vue';
import { useDebounceFn } from '@vueuse/core';
import { useVbenModal } from '@vben/common-ui';

import { Button, message, DatePicker, Input, Switch } from 'ant-design-vue';

import type { VxeGridProps } from '#/adapter/vxe-table';
import { useVbenVxeGrid } from '#/adapter/vxe-table';
import { useVbenForm } from '#/adapter/form';
import {
  getPurchaseDetailEditInfo,
  getSupplyList,
  getCompanyList,
  doPurchaseAdd,
  doPurchaseEdit,
  doPurchaseAgainst,
  doPurchaseApproval,
} from '#/api/purchase';
import { getDict, getAdminList } from '#/api/common';
import MaterialSku from '#/views/backend/modules/materialSku.vue';

interface RowType {
  confirm_num?: string | number;
  price?: string | number;
  dead_line?: string;
  template_no?: string;
  material_use?: string;
  single_piece?: string | number;
  other_pay_remark?: string;
  remark?: string;
  material_id?: string;
  material_name?: string;
  material_sku_id?: number;
  _X_ROW_KEY?: string;
}

const purchaseId = ref<number>();
const routerData = ref();
const formData = ref<any>({});
const dict = ref<any>({});
const submitLoading = ref(false);
const isDisabled = ref(true);
const emit = defineEmits(['fetchData']);

const keyword = ref<Record<string, any>>({
  supply_id: '',
  purchase_name: '',
  buyer_id: '',
});

const isBlOptions = [
  { value: 0, label: '不是大批量' },
  { value: 1, label: '是' },
];
const typeOptinos = [
  { value: 1, label: '春' },
  { value: 2, label: '夏' },
  { value: 3, label: '秋' },
  { value: 4, label: '冬' },
  { value: 5, label: '通用' },
];
const yearOptions = [
  { value: 2020, label: '2020' },
  { value: 2021, label: '2021' },
  { value: 2022, label: '2022' },
  { value: 2023, label: '2023' },
  { value: 2024, label: '2024' },
  { value: 2025, label: '2025' },
  { value: 2026, label: '2026' },
  { value: 2027, label: '2027' },
  { value: 2028, label: '2028' },
  { value: 2029, label: '2029' },
  { value: 2030, label: '2030' },
];

const handleAgainstToApproval = async (type: string) => {
  modalApi.lock();
  try {
    if (type == 'approval') {
      await doPurchaseApproval({ ids: [purchaseId.value] });
    } else {
      await doPurchaseAgainst({ ids: [purchaseId.value] });
    }
    message.success('操作成功');
    emit('fetchData');
    modalApi.close();
  } finally {
    modalApi.lock(false);
  }
};

const fetchData = async () => {
  const { row } = await getPurchaseDetailEditInfo({
    purchase_id: purchaseId.value,
  });
  formApi.setValues(row);
  formData.value = { ...row }; // 保留旧逻辑兼容
  // 使用 setGridOptions 更新表格数据
  if (gridApi) {
    gridApi.setGridOptions({
      data: row.bom_list || [],
    });
  }

  Object.keys(keyword.value).forEach((key: string) => {
    if (row[key]) {
      keyword.value[key] = 'initValue:' + row[key];
    }
  });
};

const supplyOptions = async ({ keyword = '' }: Record<string, any>) => {
  let quick_search = '';
  let initValue = '';
  let initKey = 'id';

  if (keyword.startsWith('initValue:')) {
    initValue = keyword.replace('initValue:', '');
  } else {
    quick_search = keyword;
  }

  const { list } = await getSupplyList({
    quick_search: quick_search,
    page: 1,
    limit: 30,
    initKey: initKey,
    initValue: initValue,
    select: true,
    supply_type: 2,
    Posted: 1,
  });

  return list.map((item: any) => ({
    label: item.SupplyNa,
    value: item.id,
  }));
};

const companyOptions = async ({ keyword = '' }: Record<string, any>) => {
  let quick_search = '';
  let initValue = '';
  let initKey = 'id';

  if (keyword.startsWith('initValue:')) {
    initValue = keyword.replace('initValue:', '');
  } else {
    quick_search = keyword;
  }

  const list = await getCompanyList({
    quick_search: quick_search,
    page: 1,
    limit: 30,
    initKey: initKey,
    initValue: initValue,
  });

  return list.map((item: any) => ({
    label: item.name,
    value: item.id,
  }));
};

const adminOptions = async ({ keyword = '' }: Record<string, any>) => {
  let quick_search = '';
  let initValue = '';
  let initKey = 'id';

  if (keyword.startsWith('initValue:')) {
    initValue = keyword.replace('initValue:', '');
  } else {
    quick_search = keyword;
  }

  const { list } = await getAdminList({
    quick_search: quick_search,
    page: 1,
    limit: 30,
    initKey: initKey,
    initValue: initValue,
    select: true,
    group_id: 7,
  });

  return list.map((item: any) => ({
    label: item.realname,
    value: item.id,
  }));
};

const init = async () => {
  const { select_list } = await getDict({
    keys: ['paymentMethod', 'paymentRule'],
    type: 2,
  });
  dict.value = select_list;

  formApi.updateSchema([
    {
      componentProps: {
        options: select_list.paymentMethod.map((item: any) => {
          const list = {
            label: item.name,
            value: item.value,
          };

          return list;
        }),
      },
      fieldName: 'fk_type',
    },
  ]);
  formApi.updateSchema([
    {
      componentProps: {
        options: select_list.paymentRule.map((item: any) => {
          const list = {
            label: item.name,
            value: item.name,
          };

          return list;
        }),
      },
      fieldName: 'fk_rule',
    },
  ]);
};

watch(isDisabled, (val) => {
  formApi.setState({ commonConfig: { disabled: val } });
});

const [Modal, modalApi] = useVbenModal({
  // class: 'w-5/6',
  appendToMain: true,
  fullscreen: true,
  showConfirmButton: false,
  showCancelButton: false,
  onOpenChange(isOpen: boolean) {
    if (isOpen) {
      routerData.value = modalApi.getData<Record<string, any>>();
      purchaseId.value = 0;
      formApi.setValues({});
      gridApi.setGridOptions({
        data: [],
      });
      Object.keys(keyword.value).forEach((key) => {
        keyword.value[key] = '';
      });
      init();

      if (routerData.value?.info?.purchase_id) {
        purchaseId.value = routerData.value?.info?.purchase_id;
      }

      if (purchaseId.value) {
        fetchData();
        isDisabled.value = true;
      } else {
        isDisabled.value = false;
      }
    }
  },
});
interface RowType {}
const gridOptions: VxeGridProps<RowType> = {
  pagerConfig: {
    enabled: false,
  },
  cellStyle({ row, column }: { row: any; column: any }) {
    if (column.field === 'dead_line') {
      return {
        color: 'red',
      };
    } else if (column.field === 'bom_need_num.purchase_num') {
      // console.log('row', row)
      if (row.bom_need_num.purchase_num > row.bom_need_num.need_num) {
        return {
          color: 'red',
        };
      }
    }
  },
  columns: [
    { type: 'seq', width: 90, title: '编号' },
    {
      field: 'operation',
      fixed: 'right',
      slots: { default: 'operation' },
      title: '操作',
      width: 60,
    },
    { field: 'material_sku_id', title: '物料sku', width: 300, visible: false },
    { field: 'material_id', title: '选择物料', width: 300, visible: false },
    { field: 'material_name', title: '选择物料', width: 300 },
    {
      field: 'confirm_num',
      title: '本次采购数量',
      width: 130,
      editRender: {},
      slots: { edit: 'confirm_num_edit' },
    },
    { field: 'unit', title: '单位', width: 60 },
    {
      field: 'price',
      title: '单价',
      width: 100,
      editRender: {},
      slots: { edit: 'price_edit' },
    },
    {
      field: 'dead_line',
      title: '预计交期',
      width: 150,
      editRender: {},
      slots: { edit: 'dead_line_edit' },
    },
    {
      field: 'template_no',
      title: '成品简码',
      width: 110,
      editRender: {},
      slots: { edit: 'template_no_edit' },
    },
    {
      field: 'material_use',
      title: '用途',
      width: 95,
      editRender: {},
      slots: { edit: 'material_use_edit' },
    },
    { field: 'single_piece', title: '单件用量', width: 95 },
    { field: 'reviced_status_text', title: '到料状态', width: 95 },
    {
      field: 'other_pay_remark',
      title: '其他结算方式备注',
      width: 190,
      editRender: {},
      slots: { edit: 'other_pay_remark_edit' },
    },
    {
      field: 'remark',
      title: '备注',
      width: 190,
      editRender: {},
      slots: { edit: 'remark_edit' },
    },
    { field: 'bom_need_num.need_num', title: 'BOM需求量', width: 130 },
    { field: 'bom_need_num.purchase_num', title: 'BOM已采购量', width: 130 },
  ],
  exportConfig: {},
  editConfig: {
    mode: 'cell',
    trigger: 'click',
  },
  height: '500px',
  keepSource: false,
  data: [],
  showOverflow: false,
};

const handleUpdate = async () => {
  isDisabled.value = !isDisabled.value;
};

const handleRowDelete = async (row: RowType) => {
  if (gridApi) {
    const currentData = gridApi.grid.getData();
    const index = currentData.findIndex(
      (item: any) => item._X_ROW_KEY === row._X_ROW_KEY,
    );

    console.log('row', row);
    console.log('currentData', currentData);
    if (index !== -1) {
      currentData.splice(index, 1);
      gridApi.setGridOptions({
        data: currentData,
      });
    }
  }
};

const fkChangeJoin = (value: any) => {
  const rules = dict.value.paymentRule.map((item: any) => ({
    label: item.name,
    value: item.name,
    disabled: item.value !== value,
  }));
  formApi.updateSchema([
    {
      fieldName: 'fk_rule',
      componentProps: {
        options: rules,
      },
    },
  ]);
  formApi.setValues({
    fk_rule: undefined,
  });
};
const opendAddSku = () => {
  SkuModalApi.setData({}).open();
};

const shareData = async (res: any) => {
  console.log('shareData', res);
  if (res.list && res.list.length > 0) {
    // 获取当前表格数据
    let currentTableData = gridApi.grid.getData() || [];

    // 将选中的物料数据转换为表格需要的格式
    const newRows = res.list.map((item: any) => ({
      material_sku_id: item.material_sku_id, // 物料skuID
      material_id: item.material_id, // 物料ID
      material_name: item.material_name, // 物料名称
      price: item.check_price || 0, // 物料单价，默认为0
      unit: item.check_unit, // 单位
      // 其他字段可以设置默认值
      confirm_num: '', // 采购数量
      dead_line: '', // 预计交期
      template_no: '', // 成品简码
      material_use: '', // 用途
      single_piece: '', // 单件用量
      other_pay_remark: '', // 其他结算方式备注
      remark: '', // 备注
      bom_need_num: {
        need_num: 0,
        purchase_num: 0,
      },
    }));

    // 合并现有数据和新数据
    const updatedTableData = [...currentTableData, ...newRows];

    // 更新表格数据
    gridApi.setGridOptions({
      data: updatedTableData,
    });
    message.success(`成功添加 ${res.list.length} 条物料`);
  } else {
    message.warning('未选择任何物料');
  }
};
const handleSubmit = useDebounceFn(async () => {
  await onSubmit();
}, 300);

async function onSubmit() {
  const { valid } = await formApi.validate();
  if (valid) {
    submitLoading.value = true;
    try {
      let saveData = await formApi.getValues();
      if (gridApi) {
        const tableData = gridApi.grid.getData();
        saveData.bom_list = tableData;
      }
      if (purchaseId.value) {
        await doPurchaseEdit({ ...saveData, purchase_id: purchaseId.value });
      } else {
        await doPurchaseAdd(saveData);
      }
      message.success('保存成功');
      emit('fetchData');
      modalApi.close();
    } finally {
      submitLoading.value = false;
    }
  }
}

const handleClose = async () => {
  modalApi.close();
};

const [Form, formApi] = useVbenForm({
  commonConfig: {
    disabled: isDisabled.value,
    componentProps: {
      class: 'w-full',
    },
  },
  showDefaultActions: false,
  layout: 'horizontal',
  schema: [
    {
      component: 'DatePicker',
      fieldName: 'purchase_time',
      label: '采购时间',
      componentProps: {
        class: 'w-full',
        type: 'date',
        clearable: true,
        placeholder: '请选择采购时间',
        format: 'YYYY-MM-DD',
        valueFormat: 'YYYY-MM-DD',
      },
    },
    {
      component: 'ApiSelect',
      fieldName: 'purchase_name',
      label: '下单人',
      componentProps: () => ({
        api: companyOptions,
        filterOption: false,
        onSearch: useDebounceFn((value: string) => {
          keyword.value.purchase_name = value;
        }, 300),
        params: {
          keyword: keyword.value.purchase_name || undefined,
        },
        showSearch: true,
        immediate: false,
        alwaysLoad: true,
        allowClear: true,
        maxTagCount: 'responsive',
        visibleEvent: 'onFocus',
        onDropdownVisibleChange: (open: boolean) => {
          if (open) keyword.value.purchase_name = '';
        },
      }),
    },
    {
      component: 'ApiSelect',
      fieldName: 'buyer_id',
      label: '采购员',
      componentProps: () => ({
        api: adminOptions,
        filterOption: false,
        onSearch: useDebounceFn((value: string) => {
          keyword.value.buyer_id = value;
        }, 300),
        params: {
          keyword: keyword.value.buyer_id || undefined,
        },
        showSearch: true,
        immediate: false,
        alwaysLoad: true,
        allowClear: true,
        maxTagCount: 'responsive',
        visibleEvent: 'onFocus',
        onDropdownVisibleChange: (open: boolean) => {
          if (open) keyword.value.buyer_id = '';
        },
      }),
    },
    {
      component: 'Select',
      fieldName: 'year',
      label: '年份',
      componentProps: {
        placeholder: '请选择年份',
        options: yearOptions,
      },
    },
    {
      component: 'Select',
      fieldName: 'type',
      label: '采购订单属性',
      componentProps: {
        placeholder: '请选择采购订单属性',
        options: typeOptinos,
      },
    },
    {
      component: 'ApiSelect',
      fieldName: 'supply_id',
      label: '供应商',
      componentProps: () => ({
        api: supplyOptions,
        filterOption: false,
        onSearch: useDebounceFn((value: string) => {
          keyword.value.supply_id = value;
        }, 300),
        params: {
          keyword: keyword.value.supply_id || undefined,
        },
        showSearch: true,
        immediate: false,
        alwaysLoad: true,
        allowClear: true,
        maxTagCount: 'responsive',
        visibleEvent: 'onFocus',
        onDropdownVisibleChange: (open: boolean) => {
          if (open) keyword.value.supply_id = '';
        },
      }),
    },
    {
      component: 'Switch',
      fieldName: 'first_order',
      label: '首单',
      componentProps: {
        class: 'w-[60px]',
      },
    },
    {
      component: 'Select',
      fieldName: 'is_bl',
      label: '是否大批量备料',
      componentProps: {
        placeholder: '是否大批量备料',
        options: isBlOptions,
      },
    },
    {
      component: 'Select',
      fieldName: 'fk_type',
      label: '结算方式',
      componentProps: {
        placeholder: '请选择结算方式',
        onChange: (value: any) => {
          // console.log('改变了', value)
          fkChangeJoin(value);
        },
      },
    },
    {
      component: 'Select',
      fieldName: 'fk_rule',
      label: '结算规则',
      componentProps: () => ({
        placeholder: '请选择结算规则',
      }),
    },
    {
      component: 'Input',
      fieldName: 'purchase_sn',
      label: '手工单号',
      componentProps: {
        disabled: true,
        placeholder: '自动生成',
      },
    },
    {
      component: 'Input',
      fieldName: 'sg_purchase_sn',
      label: '自定义手工单号',
      componentProps: {
        placeholder: '请输入自定义手工单号',
      },
    },
  ],
  wrapperClass: 'grid grid-cols-6',
});

const [Grid, gridApi] = useVbenVxeGrid({
  gridOptions,
});

const [SkuModal, SkuModalApi] = useVbenModal({
  connectedComponent: MaterialSku,
});
</script>
<template>
  <Modal title="物料采购单">
    <div class="p-4">
      <Form />
      <div class="my-2 flex items-center justify-between">
        <h3 class="text-lg font-medium">物料列表</h3>
        <Button :disabled="isDisabled" type="primary" @click="opendAddSku()"
          >新增物料</Button
        >
      </div>
      <Grid>
        <template #operation="{ row }">
          <Button
            :disabled="isDisabled"
            danger
            size="small"
            @click="handleRowDelete(row)"
            >删除</Button
          >
        </template>
        <template #confirm_num_edit="{ row }">
          <Input v-model:value="row.confirm_num" :disabled="isDisabled" />
        </template>
        <template #price_edit="{ row }">
          <Input v-model:value="row.price" :disabled="isDisabled" />
        </template>

        <template #dead_line_edit="{ row }">
          <DatePicker
            :disabled="isDisabled"
            type="date"
            clearable="true"
            placeholder="请选择预计交期"
            v-model:value="row.dead_line"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
            placement="bottomLeft"
            :get-popup-container="
              (triggerNode) =>
                (triggerNode.parentNode as HTMLElement) || triggerNode
            "
          />
        </template>
        <template #template_no_edit="{ row }">
          <Input v-model:value="row.template_no" :disabled="isDisabled" />
        </template>

        <template #material_use_edit="{ row }">
          <Input v-model:value="row.material_use" :disabled="isDisabled" />
        </template>
        <template #single_piece_edit="{ row }">
          <Input v-model:value="row.single_piece" :disabled="isDisabled" />
        </template>
        <template #other_pay_remark_edit="{ row }">
          <Input v-model:value="row.other_pay_remark" :disabled="isDisabled" />
        </template>
        <template #remark_edit="{ row }">
          <Input v-model:value="row.remark" :disabled="isDisabled" />
        </template>
      </Grid>
    </div>
    <template #prepend-footer>
      <Button @click="handleClose()">取消</Button>
      <template v-if="purchaseId">
        <Button
          class="bg-[#f56c6c] text-white"
          @click="
            handleAgainstToApproval(formData.Posted ? 'against' : 'approval')
          "
        >
          {{ formData.Posted ? '反审' : '审核' }}
        </Button>
        <Button
          v-if="!formData.Posted && isDisabled"
          class="bg-[#f0a62f] text-[#fff]"
          @click="handleUpdate()"
          >修改</Button
        >
      </template>
      <Button
        v-if="!isDisabled || !purchaseId"
        type="primary"
        :loading="submitLoading"
        :disabled="submitLoading"
        @click="handleSubmit"
        >保存</Button
      >
    </template>

    <SkuModal @share-data="shareData" />
  </Modal>
</template>

<style lang="scss" scoped>
.fixed-width-select {
  width: 160px;
}
</style>
